package com.graduation.smartparkingplatform.Utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.graduation.smartparkingplatform.Pojo.SpaceAll;
import com.graduation.smartparkingplatform.Service.SpaceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
@Order(1)
public class InitServlet implements InitializingBean {

  @Autowired SpaceService spaceService;
  @Autowired RedisTemplate redisTemplate;

  // 修改序列化方式
  @Autowired(required = false)
  public void setRedisTemplate(RedisTemplate redisTemplate) {
    RedisSerializer stringSerializer = new StringRedisSerializer();
    redisTemplate.setKeySerializer(stringSerializer);
    redisTemplate.setValueSerializer(stringSerializer);
    redisTemplate.setHashKeySerializer(stringSerializer);
    redisTemplate.setHashValueSerializer(stringSerializer);
    this.redisTemplate = redisTemplate;
  }

  @Override
  public void afterPropertiesSet() throws Exception {
    // 初始化操作处理
    try {
      List<SpaceAll> spaceList = spaceService.getSpaceLists();
      for (SpaceAll spaceAll : spaceList) {
        redisTemplate
            .opsForValue()
            .set(
                "spaceNo_" + spaceAll.getSpace_no(),
                JSON.toJSONString(spaceAll, SerializerFeature.WriteMapNullValue));
      }
      redisTemplate.opsForValue().set("Railing_in", "sys_close");
      redisTemplate.opsForValue().set("Railing_out", "sys_close");
      log.info("init Redis");
    } catch (Exception e) {
      log.error("init Redis error-", e);
    }
  }
}
